/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package giuliani_mapelli_marocco.business;

import giuliani_mapelli_marocco.entity.Group;
import giuliani_mapelli_marocco.entity.User;
import giuliani_mapelli_marocco.enumerations.InternalMessageType;
import java.security.Principal;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;


@Stateless
public class UserManager {

    @PersistenceContext
    EntityManager em;
    
    @Inject
    Principal principal;

    /**
     *save a new user, setting by default his calendar private
     * @param user new user to be inserted in the db
     * @return USERNAME_ALREADY_USED, EMAIL_ALREADY_USED or NO_ERRORS message type. 
     */
    public String save(User user) {
        user.setGroupName(Group.USER);
        user.setCalendarPublic(false);
        int usernameFound;
        usernameFound =  em.createNamedQuery("User.findByUsername").setParameter("username", user.getUsername()).getResultList().size();
        int mailFound = em.createNamedQuery("User.findByEmail").setParameter("email", user.getEmail()).getResultList().size();
        
        if(usernameFound != 0) {
            return InternalMessageType.USERNAME_ALREADY_USED.getMessageContent();
        } 
        if (mailFound != 0) {
            return InternalMessageType.EMAIL_ALREADY_USED.getMessageContent();
        }
        
        em.persist(user);
        return InternalMessageType.NO_ERRORS.getMessageContent();

    }

    public void unregister() {
        em.remove(getLoggedUser());
    }

    /**
     *getter of the logged user
     * @return the logger user
     */
    public User getLoggedUser() {
        return em.find(User.class, principal.getName());
    }

    /**
     * change the visibility of the calendar of the logged user
     * @param user
     */
    public void changeVisibility(User user) {
        
        user.setCalendarPublic(!(user.getCalendarPublic()));
        em.merge(user);
        
    }
    
    /**
     * finds in the db the user with the selected username
     * @param username username of the user to be found
     * @return the user from the db
     */
    public User findUserByUsername(String username) {
        
        Query q = em.createNamedQuery("User.findByUsername");
        q.setParameter("username", username);
        User u = (User)q.getSingleResult(); 
        
        return u;
        
        
        
    }


    
}
